package com.xtgg.baby;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.RequestParams;
import com.xtgg.R;
import com.xtgg.login.LoginActivity;
import com.xtgg.manager.BaseActivity;
import com.xtgg.model.Resp;
import com.xtgg.sys.Constants;
import com.xtgg.sys.DemoApp;
import com.xtgg.util.MgqDataHandler;
import com.xtgg.util.MgqRestClient;
import com.xtgg.util.PreferencesUtils;
import com.xtgg.util.TLog;
import com.xtgg.util.ToastUtil;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public class DeviceListActivity extends BaseActivity implements OnClickListener {
	MyAdapter mAdapter;
	JSONArray mArray = null;
	int mSelected = -1;
	
	ArrayList<String> mAddress = new ArrayList<String>();
	BleReceiver mReceiver;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_device_list);

		sendCheckHttpRequest();
		((TextView) findViewById(R.id.center)).setText("添加设备");
		findViewById(R.id.left).setOnClickListener(this);

		((Button)findViewById(R.id.left)).setText("取消");
		((Button)findViewById(R.id.left)).setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
		
		final PullToRefreshListView ptrlvHeadlineNews = (PullToRefreshListView) findViewById(R.id.listview);
		ptrlvHeadlineNews
				.setMode(com.handmark.pulltorefresh.library.PullToRefreshBase.Mode.DISABLED);
		ptrlvHeadlineNews
				.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
					@Override
					public void onRefresh(
							PullToRefreshBase<ListView> refreshView) {
					}
				});

		ListView listview = ptrlvHeadlineNews.getRefreshableView();
		mAdapter = new MyAdapter();
		listview.setAdapter(mAdapter);
		listview.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
			}
		});
		
		mReceiver = new BleReceiver();
		IntentFilter localIntentFilter = new IntentFilter();
	    localIntentFilter.addAction("com.fb.ble.action.device_connect");
	    registerReceiver(mReceiver, localIntentFilter);
	}

	protected void onDestroy()
	{
		super.onDestroy();
		unregisterReceiver(mReceiver);
	}
	
	class MyAdapter extends BaseAdapter implements OnClickListener {
		public int getCount() {
			return mArray != null ? mArray.size() : 0;
		}

		public Object getItem(int position) {
			return null;
		}

		public long getItemId(int position) {
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			FoodHolder foodHold = null;

			if (convertView == null) {
				LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				foodHold = new FoodHolder();

				convertView = mInflater.inflate(R.layout.item_device, null);
				foodHold.name = (TextView) convertView.findViewById(R.id.name);
				foodHold.status = (TextView) convertView.findViewById(R.id.status);

				convertView.setTag(foodHold);
			} else {
				foodHold = (FoodHolder) convertView.getTag();
			}

			JSONObject item = mArray.getJSONObject(position);
			foodHold.name.setText(item.getString("name"));
			foodHold.status.setTag(String.valueOf(position));
			
			if(mAddress.contains(item.getString("address")))
			{
				foodHold.status.setBackgroundResource(0);
				foodHold.status.setTextColor(Color.parseColor("#808080"));
				foodHold.status.setText("已经连接");
				foodHold.status.setOnClickListener(null);
			}
			else
			{
				foodHold.status.setBackgroundResource(R.drawable.selector_orange);
				foodHold.status.setTextColor(Color.parseColor("#ffffff"));
				foodHold.status.setText("添加");
				foodHold.status.setOnClickListener(this);
			}
			
			return convertView;
		}

		@Override
		public void onClick(View arg0) {
			mSelected = Integer.valueOf((String)arg0.getTag());
			connect();
		}
	}

	public final class FoodHolder {
		public TextView name;
		public TextView status;
	}
	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.left:
			showMainView();
			break;
		}
	}

	private void sendBoundHttpRequest(final Intent intent) {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);
				if (ruser.getString("state").equals("1")) {
					JSONObject obj = ruser.getJSONArray("data").getJSONObject(0);
					
					if(obj.getString("andriod_code").length() == 0)
					{
						sendCheckHttpRequest(obj.getString("deviceid"),intent);
					}
					else
					{
						Intent intent = new Intent(DeviceListActivity.this, BabyBoundListActivity.class);
						intent.putExtra("info", intent.getStringExtra("info"));
						intent.putExtra("deviceid", obj.getString("deviceid"));
						startActivity(intent);
						
						finish();
					}
				}
				else if (ruser.getString("state").equals("2"))
				{
					showExitDialog();
				} else {
					ToastUtil.showToastWithAlertPic(ruser.getString("message"));
				}
			}
		};

		JSONObject obj = JSON.parseObject(intent.getStringExtra("info"));
		
		RequestParams params = new RequestParams();
		params.put("act", "connectNewDevice");
		params.put("userid", PreferencesUtils.getString(this, "userid"));
		params.put("devicenumber",intent.getStringExtra("serial"));
		params.put("andriod_code", obj.getString("address"));
		params.put("devicemodel", intent.getStringExtra("model"));
		params.put("password", "111111");
		params.put("nickname", obj.getString("name"));
		params.put("longitude", ((DemoApp)getApplicationContext()).mLng);
		params.put("latitude", ((DemoApp)getApplicationContext()).mLat);
		params.put("power", String.valueOf(intent.getExtras().getInt("batty")));

		MgqRestClient.get(Constants.DEVICEMGT, params, loginHandler);
	}
	
	private void sendCheckHttpRequest(final String deviceId,final Intent intent) {
		MgqDataHandler loginHandler = new MgqDataHandler(this,
				true, false) {
			@Override
			public void onSuccess(String response) {
				TLog.d(TAG, "response=" + response);
				Resp ruser = JSON.parseObject(response, Resp.class);

				if (ruser.getState().equals("1")) {
					Intent intent = new Intent(DeviceListActivity.this, BabyBoundListActivity.class);
					intent.putExtra("info", intent.getStringExtra("info"));
					intent.putExtra("deviceid", deviceId);
					startActivity(intent);
					
					finish();
				} 
				else if (ruser.getState().equals("2"))
				{
					showExitDialog();
				}
				else 
				{
					
				}
			}
		};

		JSONObject obj = JSON.parseObject(intent.getStringExtra("info"));
		RequestParams params = new RequestParams();
		params.put("act", "updateDeviceInfo");
		params.put("deviceid", deviceId);
		params.put("andriod_code", obj.getString("address"));
		params.put("ios_code", obj.getString("ios_code"));

		MgqRestClient.get(Constants.SETTING, params, loginHandler);
	}
	
	Handler mHandle = new Handler()
	{
		@SuppressLint("NewApi")
		public void handleMessage(Message msg)
		{
			if(msg.what == 1)
			{
				BluetoothGattService localBluetoothGattService = mConnect.getService(UUID.fromString("0000180A-0000-1000-8000-00805f9b34fb"));
				if(localBluetoothGattService != null)
				{
					BluetoothGattCharacteristic localBluetoothGattCharacteristic = localBluetoothGattService.getCharacteristic(UUID.fromString("00002a24-0000-1000-8000-00805f9b34fb"));
					mConnect.readCharacteristic(localBluetoothGattCharacteristic);
			
				}
				else
				{
					ToastUtil.showToastWithAlertPic("服务信息不存在");
					disMissDailog();
				}
			}
			else if(msg.what == 2)
			{
				BluetoothGattService localBluetoothGattService = mConnect.getService(UUID.fromString("0000180F-0000-1000-8000-00805f9b34fb"));
				if(localBluetoothGattService != null)
				{
					BluetoothGattCharacteristic localBluetoothGattCharacteristic = localBluetoothGattService.getCharacteristic(UUID.fromString("00002a19-0000-1000-8000-00805f9b34fb"));
					mConnect.readCharacteristic(localBluetoothGattCharacteristic);
				}
				else
				{
					ToastUtil.showToastWithAlertPic("服务信息不存在");
					disMissDailog();
				}
			}
			else if(msg.what == 0)
			{
				BluetoothGattService localBluetoothGattService = mConnect.getService(UUID.fromString("0000180A-0000-1000-8000-00805f9b34fb"));
				if(localBluetoothGattService != null)
				{
					BluetoothGattCharacteristic localBluetoothGattCharacteristic = localBluetoothGattService.getCharacteristic(UUID.fromString("00002a25-0000-1000-8000-00805f9b34fb"));
					mConnect.readCharacteristic(localBluetoothGattCharacteristic);
				}
				else
				{
					ToastUtil.showToastWithAlertPic("服务信息不存在");
					disMissDailog();
				}
			}
			else if(msg.what == 3)
			{
				int left = mBatty.charAt(0); 
	    		
	    		Intent in = new Intent(DeviceListActivity.this,BabyDeviceNumberActivity.class);
				in.putExtra("info", JSON.toJSONString(mArray.getJSONObject(mSelected)));
				in.putExtra("model", mModel);
				in.putExtra("batty", left);
				in.putExtra("serial", mSerial);
	    		
	    		sendBoundHttpRequest(in);
			}
		}
	};
	
	String mModel = "";
	String mSerial = "";
	String mBatty = "";
	
	GattCallback mGattCallback = new GattCallback();
	@SuppressLint("NewApi")
	private class GattCallback extends BluetoothGattCallback
	{
		private GattCallback()
		{
	    }
		
		public void onCharacteristicChanged(final BluetoothGatt paramBluetoothGatt, BluetoothGattCharacteristic paramBluetoothGattCharacteristic)
	    {
			
/*	      if (paramBluetoothGattCharacteristic.getValue()[0] == 1)
	      {
	        if (!isPreviousCommandHandling)
	          break label87;
	        Log.i("CALM", "ACTION_DEV_DOUBLE_CLICK---------");
	        BleService.this.mCommandHanler.removeCallbacksAndMessages(null);
	        BleService.this.isPreviousCommandHandling = false;
	        if (SettingSp.getInstance(BleService.this).getDoubleClick() == 0)
	          BleService.this.broadcastUpdate("com.fb.ble.action.find_waring", paramBluetoothGatt.getDevice().getAddress());
	      }
	      else
	      {
	        return;
	      }
	      BleService.this.broadcastUpdate("com.fb.ble.action.audio_record");
	      return;
	      label87: BleService.this.isPreviousCommandHandling = true;
	      BleService.this.mCommandHanler.postDelayed(new Runnable()
	      {
	        public void run()
	        {
	          BleService.this.isPreviousCommandHandling = false;
	          BleService.this.broadcastUpdate("com.fb.ble.action.device_single_click", paramBluetoothGatt.getDevice().getAddress(), paramBluetoothGatt.getDevice().getName());
	          Log.i("CALM", "ACTION_DEV_SINGLE_CLICK-------------------");
	        }
	      }
	      , 500L);*/
	    }

		@SuppressWarnings("deprecation")
	    public void onCharacteristicRead(BluetoothGatt paramBluetoothGatt, BluetoothGattCharacteristic paramBluetoothGattCharacteristic, int paramInt)
	    {
	    	if(mSerial.length() == 0) 
	    	{
	    		mSerial = new String(paramBluetoothGattCharacteristic.getValue());
			/*	final Handler handle = new Handler()
				{
					public void handleMessage(Message msg)
					{
						BluetoothGattService localBluetoothGattService = mConnect.getService(UUID.fromString("0000180A-0000-1000-8000-00805f9b34fb"));
						if(localBluetoothGattService != null)
						{
							BluetoothGattCharacteristic localBluetoothGattCharacteristic = localBluetoothGattService.getCharacteristic(UUID.fromString("00002a24-0000-1000-8000-00805f9b34fb"));
					        mConnect.readCharacteristic(localBluetoothGattCharacteristic);
						}
					}
				};
				
				new Timer().schedule(new TimerTask()
				{
					@Override
					public void run() {
						mHandle.sendEmptyMessage(1);
					}
				}, 500);*/
	    		mHandle.sendEmptyMessage(1);
	    	}
	    	else if(mModel.length() == 0)
	    	{
	    		mModel = new String(paramBluetoothGattCharacteristic.getValue());
			/*	final Handler handle = new Handler()
				{
					public void handleMessage(Message msg)
					{
						BluetoothGattService localBluetoothGattService = mConnect.getService(UUID.fromString("0000180F-0000-1000-8000-00805f9b34fb"));
						if(localBluetoothGattService != null)
						{
							BluetoothGattCharacteristic localBluetoothGattCharacteristic = localBluetoothGattService.getCharacteristic(UUID.fromString("00002a19-0000-1000-8000-00805f9b34fb"));
					        mConnect.readCharacteristic(localBluetoothGattCharacteristic);
						}
					}
				};
				
	    		
				new Timer().schedule(new TimerTask()
				{
					@Override
					public void run() {
						mHandle.sendEmptyMessage(2);
					}
				}, 500);*/
				
				mHandle.sendEmptyMessage(2);
	    	}
	    	else if(mBatty.length() == 0)
	    	{
	    		mBatty = new String(paramBluetoothGattCharacteristic.getValue());
	    	}
	    	
	    	if(mSerial.length() > 0 && mModel.length() > 0 && mBatty.length() > 0)
	    	{
	    		mConnect.close();
	    		mHandle.sendEmptyMessage(3);
	    	}
	    }

		public void onConnectionStateChange(BluetoothGatt paramBluetoothGatt, int paramInt1, int paramInt2)
	    {
	    	Intent intent = null;
	    	
	    	if(paramInt2 == BluetoothProfile.STATE_CONNECTED)
	    	{
	    		if(!((DemoApp)getApplicationContext()).deviceInfo.contains(paramBluetoothGatt))
	    		{
	    			intent = new Intent("com.fb.ble.action.device_connect");
	    			((DemoApp)getApplicationContext()).deviceInfo.add(paramBluetoothGatt);
	    			intent.putExtra("connect", "1");
	    		}
	    	}
	    	else if(paramInt2 == BluetoothProfile.STATE_DISCONNECTED)
	    	{
	    		if(((DemoApp)getApplicationContext()).deviceInfo.contains(paramBluetoothGatt))
	    		{
	    			intent = new Intent("com.fb.ble.action.device_connect");
	    			((DemoApp)getApplicationContext()).deviceInfo.remove(paramBluetoothGatt);
	    			intent.putExtra("connect", "0");
	    		}
	    	}
	    	
	    	if(intent != null)
	    	{
    			intent.putExtra("address", paramBluetoothGatt.getDevice().getAddress());
	    		sendBroadcast(intent);
	    	}
	    }

	    public void onReadRemoteRssi(BluetoothGatt paramBluetoothGatt, int paramInt1, int paramInt2)
	    {
	    }

	    public void onServicesDiscovered(BluetoothGatt paramBluetoothGatt, int paramInt)
	    {
	      if (paramInt == 0)
	      {
	    	  
	 /*       BleService.this.broadcastUpdate("com.fb.ble.action.device_gatt_services_discovered", paramBluetoothGatt.getDevice().getAddress());
	        BleService.this.enablePeerDeviceNotifyMe(paramBluetoothGatt, true);
	        UUID localUUID1 = BleGattAttributes.UUID_IMMIDIATE_ALERT_SERVICEL;
	        UUID localUUID2 = BleGattAttributes.UUID_ALERT_LEVEL_CHARACTERISTIC;
	        paramBluetoothGatt.readCharacteristic(BleService.this.getCharacteristic(paramBluetoothGatt.getDevice().getAddress(), localUUID1, localUUID2));*/
	      }
	    }
	}
	
	BluetoothGatt mConnect;
	@SuppressLint("NewApi")
	public void connect()
	{
		showWaiting("正在连接设备...");
		BluetoothDevice localBluetoothDevice = ((DemoApp)getApplicationContext()).mBluetoothAdapter
				.getRemoteDevice(mArray.getJSONObject(mSelected).getString("address"));
		mConnect = localBluetoothDevice.connectGatt(this, false,mGattCallback);
	}
	
//	private static final UUID Battery_Service_UUID = UUID.fromString("0000180F-0000-1000-8000-00805f9b34fb");
//    private static final UUID Battery_Level_UUID = UUID.fromString("00002a19-0000-1000-8000-00805f9b34fb");
    
	
	public class BleReceiver extends BroadcastReceiver
	{
		@SuppressLint("NewApi")
		public void onReceive(Context paramContext, Intent paramIntent)
	    {
			if (paramIntent.getAction().equals("com.fb.ble.action.device_connect"))
			{
				if(mSelected == -1) return;
				
				if(paramIntent.getStringExtra("connect").equals("1"))
				{
					mConnect.connect();
					mConnect.discoverServices();
				}
				/*
				final Handler handle = new Handler()
				{
					public void handleMessage(Message msg)
					{
						BluetoothGattService localBluetoothGattService = mConnect.getService(UUID.fromString("0000180A-0000-1000-8000-00805f9b34fb"));
						if(localBluetoothGattService != null)
						{
							BluetoothGattCharacteristic localBluetoothGattCharacteristic = localBluetoothGattService.getCharacteristic(UUID.fromString("00002a25-0000-1000-8000-00805f9b34fb"));
					        mConnect.readCharacteristic(localBluetoothGattCharacteristic);
						}
					}
				};*/
				
				new Timer().schedule(new TimerTask()
				{
					@Override
					public void run() {
						mHandle.sendEmptyMessage(0);
					}
				}, 500);
			}
	    }
	}
	
	private void sendCheckHttpRequest() {
		MgqDataHandler loginHandler = new MgqDataHandler(this,
				true, false) {
			@Override
			public void onSuccess(String response) {
				TLog.d(TAG, "response=" + response);
				Resp ruser = JSON.parseObject(response, Resp.class);

				if (ruser.getState().equals("1")) {
					JSONArray obj = JSON.parseObject(response).getJSONArray(
							"data");
					int count = obj.size();
					for(int i = 0; i < count; i++)
					{
						mAddress.add(obj.getJSONObject(i).getString("andriod_code"));
					}
				} 
				else if (ruser.getState().equals("2"))
				{
					showExitDialog();
				} 
				else 
				{
					
				}
				
				mArray = JSON.parseArray(getIntent().getStringExtra("array"));
				mAdapter.notifyDataSetChanged();
			}
		};

		RequestParams params = new RequestParams();
		params.put("act", "getMyDeviceList");
		params.put("userid", PreferencesUtils.getString(this, "userid"));

		MgqRestClient.get(Constants.DEVICEMGT, params, loginHandler);
	}
}
